package com.oriole.admin.config.interceptor;

import com.oriole.common.constant.Constants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Date: 2020/8/14 23:48
 * description: Feign的拦截器，Feign在发送网络请求之前会执行以下的拦截器
 */
@Component
public class JwtFeignInterceptor implements RequestInterceptor {

    private static final Logger log = LoggerFactory.getLogger(JwtFeignInterceptor.class);

    @Override
    public void apply(RequestTemplate template) {
        if (Constants.PATHS_PERMIT_LOCAL.contains(template.path())) {
            log.debug("local login is not need a header token by path {}", template.path());
        } else {
            if (!template.headers().containsKey(Constants.HEADER_STRING)) {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    String token = request.getHeader(Constants.HEADER_STRING);
                    if (StringUtils.isNotBlank(token)) {
                        template.header(Constants.HEADER_STRING, Constants.TOKEN_PREFIX + token);
                    }
                }
            }
        }
    }

}
